import { request } from '@umijs/max';
import type {
  ApiFunction,
  ApiParams,
  ApiRequestOptions,
  ApiReturnType,
  RequestMethod,
} from './type';
export const HOST = '/dev-api';

export const createApi = <T extends ApiParams>(api: T): ApiReturnType<T> => {
  if (typeof api === 'string') {
    const apiFunction: ApiFunction = async ({
      data = {},
      path = {},
      query = {},
      ...rest
    }: ApiRequestOptions = {}) => {
      const [method] = api.match(/GET|POST|PUT|DELETE|HEAD/) || [];
      if (!method) throw new Error('未指定请求方法');
      let url = api.replace(method, '').trim();
      Object.entries(path).forEach(([key, value]) => {
        url = url.replace(`{${key}}`, value?.toString());
      });
      const options = {
        method: method as RequestMethod,
        params: query,
        data,
        ...rest,
      };
      return request(`${HOST}${url}`, options);
    };
    return apiFunction as unknown as ApiReturnType<T>;
  } else if (typeof api === 'object' && api !== null) {
    return Object.fromEntries(
      Object.entries(api).map(([key, value]) => [key, createApi(value)]),
    ) as ApiReturnType<T>;
  }
  throw new Error('错误的API配置');
};
